/**
 * Copyright (c) 2016-2020 https://github.com/zhaohuatai
 *
 * contact 824069438@qq.com
 *  
 */
package org.zfes.snowy.auth.shiro.jwt.mgt;

import javax.servlet.http.HttpServletRequest;
import org.apache.shiro.mgt.SessionStorageEvaluator;
import org.apache.shiro.session.mgt.NativeSessionManager;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.AntPathMatcher;
import org.apache.shiro.util.PatternMatcher;
import org.apache.shiro.web.subject.WebSubject;
import org.apache.shiro.web.util.WebUtils;
import org.zfes.snowy.auth.shiro.jwt.token.JWTTokenParser;
import org.zfes.snowy.core.consts.FrameConst;
import org.zfes.snowy.core.util.ZWebUtil;
/**
 * 带有 snowy-jwt-access-token 的请求，则为jwt 认证请求，所以不要产生session<br>
 * jwt登陆请求也不用产生session
 * @author root
 *
 */
public class SnowySessionStorageEvaluator implements SessionStorageEvaluator {

	private  String jwtTokenLoginUrl;
	protected PatternMatcher pathMatcher = new AntPathMatcher();
	private SessionManager sessionManager;
	 
	@Override
	public boolean isSessionStorageEnabled(Subject subject) {
		   if (subject.getSession(false) != null) {
	            //use what already exists
	            return true;
	        }
		   if(WebUtils.isWeb(subject)) {
			   HttpServletRequest httpRequest = WebUtils.getHttpRequest(subject);
			   
			   boolean isjwtLogin= ZWebUtil.pathsMatch(jwtTokenLoginUrl, httpRequest);
			   if(isjwtLogin){
				   return false;
			   }
			   
			   String jwtAuthToken=JWTTokenParser.getTokenFromRequest(httpRequest,FrameConst.TOKENS.JWT_AUTH_TOKEN);
			   if(jwtAuthToken!=null&&!jwtAuthToken.isEmpty()){
				   return false;
			   }
		   }

	        //SHIRO-350: non-web subject instances can't be saved to web-only session managers:
	        //since 1.2.1:
	        if (!(subject instanceof WebSubject) && (this.sessionManager != null && !(this.sessionManager instanceof NativeSessionManager))) {
	            return false;
	        }

	        return WebUtils._isSessionCreationEnabled(subject);
	}


	public String getJwtTokenLoginUrl() {
		return jwtTokenLoginUrl;
	}


	public void setJwtTokenLoginUrl(String jwtTokenLoginUrl) {
		this.jwtTokenLoginUrl = jwtTokenLoginUrl;
	}


	public SessionManager getSessionManager() {
		return sessionManager;
	}
	
	public void setSessionManager(SessionManager sessionManager) {
	        this.sessionManager = sessionManager;
	 }

	
	
}
